package com.shijie.service;

import com.shijie.component.ErpUserService;
import com.shijie.core.AbstractService;
import com.shijie.domain.entity.Adverts;
import com.shijie.domain.entity.Dicts;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.mapper.AdvertsMapper;
import com.shijie.mapper.DictsMapper;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class AdvertsService extends AbstractService<Adverts> {

    @Resource
    private AdvertsMapper advertsMapper;
    @Resource
    private DictsMapper dictsMapper;
    @Resource
    private ErpUserService erpUserService;

    public List<Adverts> selectAdverts(String page, String position) {
        Condition condition = new Condition(Adverts.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("status", EnumInterface.Status.VALID.ordinal());
        criteria.andEqualTo("page", page);
        criteria.andEqualTo("position", position);
        condition.orderBy("sort").asc();
        return advertsMapper.selectByCondition(condition);
    }

    public void save(Adverts adverts) {
        if (adverts.getPage() != null) {
            Dicts dict = this.getDictByVAndL(adverts.getPage(), "PAGE");
            if (dict != null) {
                adverts.setPageName(dict.getDictLabel());
            }
        }
        if (adverts.getPosition() != null) {
            Dicts dict = this
                    .getDictByVAndL(adverts.getPosition(), "POSITIONS");
            if (dict != null) {
                adverts.setPositionName(dict.getDictLabel());
            }
        }
        if (adverts.getId() == null) {
            adverts.setCreateBy(erpUserService.getUserName());
            adverts.setCreateTime(DateTime.now().toDate());
            advertsMapper.insert(adverts);
        } else {
            adverts.setUpdateBy(erpUserService.getUserName());
            adverts.setUpdateTime(DateTime.now().toDate());
            advertsMapper.updateByPrimaryKey(adverts);
        }
    }

    private Dicts getDictByVAndL(String dictValue, String dictType) {
        Dicts condition = new Dicts();
        condition.setDictType(dictType);
        condition.setDictValue(dictValue);
        return dictsMapper.selectOne(condition);
    }
}
